package com.flyduck.mall.common.upload.manager;

import cn.hutool.core.util.ArrayUtil;
import com.flyduck.ss.common.core.exception.ServiceException;
import com.flyduck.ss.common.core.utils.StringUtils;
import com.flyduck.ss.common.oss.core.OssClient;
import com.flyduck.ss.common.oss.entity.UploadResult;
import com.flyduck.ss.common.oss.factory.OssFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * UploadManager
 * </p>
 *
 * @author flyduck
 * @since 2025-01-24
 */
@Component
public class UploadManager {

    public List<String> upload(MultipartFile[] pictures) throws IOException {
        List<String> resultList = new ArrayList<>();

        //1、检查图片是否符合要求
        if (ArrayUtil.isEmpty(pictures)) {
            return new ArrayList<>();
        }

        for (MultipartFile file : pictures) {
            String originalFileName = file.getOriginalFilename();
            String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf("."), originalFileName.length());
            OssClient storage = OssFactory.instance();
            UploadResult uploadResult;
            try {
                uploadResult = storage.uploadSuffix(file.getBytes(), suffix);
            } catch (IOException e) {
                throw new ServiceException(e.getMessage());
            }
            resultList.add(uploadResult.getUrl());
        }
        return resultList;
    }
}
